What is yargs?
The yargs npm package is a command-line argument parser that helps in building interactive command line tools, by parsing arguments and generating an elegant user interface. It provides a simple and efficient way to handle command line arguments for Node.js applications.
What are yargs's main functionalities?
Command Parsing
Yargs allows you to define commands and associated options. This feature is useful for CLI applications that perform different actions based on the command provided.
const yargs = require('yargs/yargs')(process.argv.slice(2));
yargs.command('get', 'make a get HTTP request', () => {}, (argv) => {
console.log(`Request made to URL: ${argv.url}`);
}).argv;
Option Parsing
Yargs can parse options (also known as flags or switches) with additional configuration such as aliases, types, and descriptions.
const yargs = require('yargs/yargs')(process.argv.slice(2));
yargs.option('verbose', {
alias: 'v',
type: 'boolean',
description: 'Run with verbose logging'
}).argv;
Default Values
Yargs allows setting default values for options, which will be used if no value is provided by the user.
const yargs = require('yargs/yargs')(process.argv.slice(2));
yargs.default('port', 8080).argv;
Automatic Help and Version Information
Yargs can automatically generate help and version information for the CLI tool, making it easier for users to understand how to use the application.
const yargs = require('yargs/yargs')(process.argv.slice(2));
yargs.help().version().argv;
Custom Validation
Yargs provides a way to define custom validation rules for the provided arguments, ensuring that the input meets certain criteria before the application proceeds.
const yargs = require('yargs/yargs')(process.argv.slice(2));
yargs.option('port', {
describe: 'The port to bind on',
demandOption: true,
number: true
}).check((argv, options) => {
if (argv.port < 1024) {
throw new Error('Port must be at least 1024');
}
return true;
}).argv;
Other packages similar to yargs
commander
Commander is another popular npm package for parsing command-line options. It provides a high-level API for defining commands and options, similar to yargs. Commander is known for its simplicity and declarative approach to command-line arguments.
minimist
Minimist is a minimalistic command-line argument parser. It is more lightweight than yargs and focuses on parsing a list of arguments into an object, without the additional features like command handling, help text generation, or validation.
meow
Meow is a CLI helper for creating Node.js command-line apps. It provides a simpler and more opinionated API compared to yargs, with built-in help text, version output, and flag aliasing. Meow is suitable for smaller projects that require less customization.
caporal
Caporal is a full-featured framework for building command-line applications. It offers a rich set of features including argument parsing, validation, autocomplete, and more. Caporal is more framework-like compared to yargs, which might be more suitable for complex CLI tools.
Yargs
Yargs be a node.js library fer hearties tryin' ter parse optstrings
Description
Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface.
It gives you:
- commands and (grouped) options (
my-program.js serve --port=5000
). - a dynamically generated help menu based on your arguments:
mocha [spec..]
Run tests with Mocha
Commands
mocha inspect [spec..] Run tests with Mocha [default]
mocha init <path> create a client-side Mocha setup at <path>
Rules & Behavior
--allow-uncaught Allow uncaught errors to propagate [boolean]
--async-only, -A Require all tests to use a callback (async) or
return a Promise [boolean]
- bash-completion shortcuts for commands and options.
- and tons more.
Installation
Stable version:
npm i yargs
Bleeding edge version with the most recent features:
npm i yargs@next
Usage
Simple Example
#!/usr/bin/env node
const yargs = require('yargs/yargs')
const { hideBin } = require('yargs/helpers')
const argv = yargs(hideBin(process.argv)).argv
if (argv.ships > 3 && argv.distance < 53.5) {
console.log('Plunder more riffiwobbles!')
} else {
console.log('Retreat from the xupptumblers!')
}
$ ./plunder.js --ships=4 --distance=22
Plunder more riffiwobbles!
$ ./plunder.js --ships 12 --distance 98.7
Retreat from the xupptumblers!
Complex Example
#!/usr/bin/env node
const yargs = require('yargs/yargs')
const { hideBin } = require('yargs/helpers')
yargs(hideBin(process.argv))
.command('serve [port]', 'start the server', (yargs) => {
yargs
.positional('port', {
describe: 'port to bind on',
default: 5000
})
}, (argv) => {
if (argv.verbose) console.info(`start server on :${argv.port}`)
serve(argv.port)
})
.option('verbose', {
alias: 'v',
type: 'boolean',
description: 'Run with verbose logging'
})
.argv
Run the example above with --help
to see the help for the application.
Supported Platforms
TypeScript
yargs has type definitions at @types/yargs.
npm i @types/yargs --save-dev
See usage examples in docs.
Deno
As of v16
, yargs
supports Deno:
import yargs from 'https://deno.land/x/yargs/deno.ts'
import { Arguments } from 'https://deno.land/x/yargs/deno-types.ts'
yargs(Deno.args)
.command('download <files...>', 'download a list of files', (yargs: any) => {
return yargs.positional('files', {
describe: 'a list of files to do something with'
})
}, (argv: Arguments) => {
console.info(argv)
})
.strictCommands()
.demandCommand(1)
.argv
ESM
As of v16
,yargs
supports ESM imports:
import yargs from 'yargs'
import { hideBin } from 'yargs/helpers'
yargs(hideBin(process.argv))
.command('curl <url>', 'fetch the contents of the URL', () => {}, (argv) => {
console.info(argv)
})
.demandCommand(1)
.argv
Usage in Browser
See examples of using yargs in the browser in docs.
Having problems? want to contribute? join our community slack.
Documentation
Table of Contents
Supported Node.js Versions
Libraries in this ecosystem make a best effort to track
Node.js' release schedule. Here's a
post on why we think this is important.